home *** CD-ROM | disk | FTP | other *** search
- Path: news.sprintlink.net!datalytics!news
- From: Rob Stewart <stew@datalytics.com>
- Newsgroups: comp.lang.c++
- Subject: Re: beginner question - constants
- Date: 4 Jan 1996 21:25:27 GMT
- Organization: Datalytics, Inc
- Message-ID: <4chgk7$ldg@gold.datalytics.com>
- References: <4ceht0$ruj@sun.cis.smu.edu>
- NNTP-Posting-Host: pc071.datalytics.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=iso-8859-1
- Content-Transfer-Encoding: 8bit
- X-Mailer: Mozilla 1.22 (Windows; I; 32bit)
-
- dbowman@post.smu.edu (Damon Bowman) wrote:
- >
- >Can anyone explain to me the functional difference between a
- >macro-based constant and a formal constant? I understand that by
- >using the #define directive, the preprocessor replaces all instances
- >of the constant in the code with itÆs value. I also understand that
- >formal constants (using the const keyword) do not undergo this
- >replacement.
- >
- >What I donÆt understand is why one might be better than another and
- >what conditions might influence me to choose one over the other. They
- >appear to be two versions of the same thing.
- >
-
- The difference is one of type safety. When the preprocessor
- makes a textual substitution, there is no type associated with
- it (unless it happens to be something like 1.0f). The
- compiler can interpret that string as anything it likes in
- each context. A const variable has type and only allows the
- compiler to perform implicit conversions appropriate to that
- type.
-
- To overcome this, some C programmers write manifest constants
- (those declared with the #define directive) with type
- information in a cast:
-
- #define LOW_VALUE (unsigned short)1
-
- This effects the same thing as the simpler:
-
- const unsigned short LOW_VALUE = 1;
-
- --
- Robert Stewart | My opinions are usually my own.
- Datalytics, Inc.
- (513)226-7700
- stew@datalytics.com
-
-
-